package com.szewec.ps.ui.common;

import androidx.databinding.DataBindingUtil;

import android.content.Intent;
import android.os.Bundle;
import android.os.Parcel;
import android.os.Parcelable;
import android.view.View;
import android.widget.ImageView;
import android.widget.ZoomControls;

import com.alibaba.fastjson.JSON;
import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.map.PolylineOptions;
import com.baidu.mapapi.map.TextureMapView;
import com.baidu.mapapi.map.UiSettings;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.utils.DistanceUtil;
import com.szewec.ps.R;
import com.szewec.ps.base.BaseActivity;
import com.szewec.ps.base.Constants;
import com.szewec.ps.databinding.ActivitySelectCoordinatesBinding;
import com.szewec.ps.model.PresentValue;
import com.szewec.ps.myview.toast.bamtoast.BamToast;
import com.szewec.ps.util.CoorModelChangeUtil;
import com.szewec.ps.util.ListUtil;
import com.szewec.ps.util.LogUtil;
import com.szewec.ps.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.OnClick;

public class SelectCoordinatesActivity extends BaseActivity {
    private ActivitySelectCoordinatesBinding binding;
    private static final String TAG = "SelectCoordinatesActivity";
    private TextureMapView mMapView;
    private BaiduMap mBaiduMap;
    private LocationClient mLocationClient;
    private BDLocation bdlocation;
    //是否第一次定位
    private boolean isFirstLocate = true;
    //当前地图中心点坐标
    private LatLng centerPoint;
    //已添加的点
    private List<LatLng> addedPoint = new ArrayList<>();
    //总距离
    private double totalDistance = 0.0;
    //上一点距离
    private double lastPointDistance = 0.0;
    //markerIron
    private BitmapDescriptor rangingMarker = BitmapDescriptorFactory.fromResource(R.drawable.ranging_marker);
    //页面flag
    private String flag;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_select_coordinates);
        ButterKnife.bind(this);
        initMap();

        //获取页面传值
        Bundle presentValue = getIntent().getExtras();
        PresentValue<String> value = (PresentValue<String>) presentValue.getSerializable(Constants.EXTRA_KEY.SELECT_COOR);
        flag = value.getFlag();
        if (StringUtils.isNotEmpty(value.getT())){
            addedPoint = CoorModelChangeUtil.changeToLatLng(value.getT());
            //初始化点和线
            doRepaintPoint();
        }
        configTitleBar();
    }

    private void configTitleBar(){
        binding.titleBar.setLeftLayoutVisibility(View.VISIBLE);
        binding.titleBar.setLeftLayoutClickListener(this::finish);
        binding.titleBar.setRightLayoutVisibility(View.VISIBLE);
        binding.titleBar.setRightTextVisibility(View.VISIBLE);

        if (StringUtils.isNotEmpty(flag)){
            //测距
            if (flag.equals(Constants.SELECT_COOR_FLAG.RANGING)){
                binding.titleBar.setRightText("清空");
                binding.titleBar.setRightLayoutClickListener(view -> {
                    addedPoint.clear();
                    totalDistance = 0;
                    lastPointDistance = 0;
                    mBaiduMap.clear();
                    binding.tvLastPointDistance.setText("0公里");
                    binding.tvTotalDistance.setText("0公里");
                });
            }else {//选择坐标
                binding.titleBar.setRightText("确定");
                binding.titleBar.setRightLayoutClickListener(view -> {
                    String selectedCoor = CoorModelChangeUtil.changeToMyPoint(addedPoint);
                    LogUtil.i(TAG,"选择的坐标是:" + selectedCoor);
                    Intent intent = new Intent();
                    intent.putExtra(Constants.EXTRA_KEY.SELECT_COOR,selectedCoor);
                    setResult(Constants.RESULT_CODE.SELECTED_POINT,intent);
                    finish();
                });
            }
        }else {
            BamToast.showText(this,"系统出错,请联系系统管理员",1000);
        }
    }

    private void initMap(){
        // 隐藏百度的LOGO
        mMapView = binding.bmapView;
        View child = mMapView.getChildAt(1);
        if (child != null && (child instanceof ImageView || child instanceof ZoomControls)) {
            child.setVisibility(View.GONE);
        }
        // 不显示地图上比例尺
        mMapView.showScaleControl(false);
        // 不显示地图缩放控件（按钮控制栏）
        mMapView.showZoomControls(false);

        mBaiduMap = mMapView.getMap();
        //开启地图的定位图层
        mBaiduMap.setMyLocationEnabled(true);

        //通过LocationClient发起定位
        //定位初始化
        mLocationClient = new LocationClient(this);


        //通过LocationClientOption设置LocationClient相关参数
        LocationClientOption option = new LocationClientOption();
        option.setOpenGps(true); // 打开gps
        option.setCoorType("bd09ll"); // 设置坐标类型
        option.setScanSpan(1000);

        //设置locationClientOption
        mLocationClient.setLocOption(option);

        //注册LocationListener监听器
        MyLocationListener myLocationListener = new MyLocationListener();
        mLocationClient.registerLocationListener(myLocationListener);
        //开启地图定位图层
        mLocationClient.start();
        //手势
        UiSettings settings = mBaiduMap.getUiSettings();
        settings.setOverlookingGesturesEnabled(false);//屏蔽双指下拉时变成3D地图
        settings.setRotateGesturesEnabled(false);//屏蔽旋转


        mBaiduMap.setOnMapStatusChangeListener(new BaiduMap.OnMapStatusChangeListener() {
            @Override
            public void onMapStatusChangeStart(MapStatus mapStatus) {

            }

            @Override
            public void onMapStatusChangeStart(MapStatus mapStatus, int i) {

            }

            @Override
            public void onMapStatusChange(MapStatus mapStatus) {
            }

            @Override
            public void onMapStatusChangeFinish(MapStatus mapStatus) {
                centerPoint = mapStatus.target;
            }
        });
    }

    @OnClick({R.id.iv_location,R.id.rl_last_step,R.id.rl_add_point})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_location:
                //回到我的位置
                navigateTo(bdlocation, 19f);
                break;
            case R.id.rl_last_step:
                //上一步
                if (ListUtil.isNotEmpty(addedPoint)){
                    addedPoint.remove(addedPoint.size() - 1);
                    doRepaintPoint();
                }else {
                    BamToast.showText(this,"请先添加点",1000);
                }
                break;
            case R.id.rl_add_point:
                //添加
                doAddPoint();
                break;
        }
    }

    /**
     * 添加点
     */
    private void doAddPoint(){
        //添加marker
        OverlayOptions options = new MarkerOptions().icon(rangingMarker).position(centerPoint).anchor(0.5f,0.5f);
        mBaiduMap.addOverlay(options);
        addedPoint.add(centerPoint);
        //计算距离
        if (addedPoint.size() > 1){
            double dt = DistanceUtil.getDistance(centerPoint,addedPoint.get(addedPoint.size() - 2)) / 1000;
            binding.tvLastPointDistance.setText(String.format("%.1f公里",dt));
            lastPointDistance = dt;
            totalDistance += dt;
            binding.tvTotalDistance.setText(String.format("%.1f公里",totalDistance));
            OverlayOptions options1 = new PolylineOptions().width(5).color(0xAA00FF00).points(addedPoint);
            mBaiduMap.addOverlay(options1);
        }

    }

    /**
     * 重绘点和线
     */
    private void doRepaintPoint(){
        //先清空,重新画
        mBaiduMap.clear();
        totalDistance = 0.0;
        lastPointDistance = 0.0;
        for (int i=0;i<addedPoint.size();i++){
            OverlayOptions options = new MarkerOptions().icon(rangingMarker).position(addedPoint.get(i)).anchor(0.5f,0.5f);
            mBaiduMap.addOverlay(options);
            //计算距离
            if (i > 0){
                double dt = DistanceUtil.getDistance(addedPoint.get(i),addedPoint.get(i-1)) / 1000;
                totalDistance += dt;
                if (i == addedPoint.size() - 1){
                    lastPointDistance = dt;
                }
            }
        }
        if (addedPoint.size() > 1){//两个点以上
            OverlayOptions options1 = new PolylineOptions().width(5).color(0xAA00FF00).points(addedPoint);
            mBaiduMap.addOverlay(options1);
        }
        binding.tvTotalDistance.setText(String.format("%.1f公里",totalDistance));
        binding.tvLastPointDistance.setText(String.format("%.1f公里",lastPointDistance));
    }

    public class MyLocationListener extends BDAbstractLocationListener {
        @Override
        public void onReceiveLocation(BDLocation location) {
            //mapView 销毁后不在处理新接收的位置
            if (location == null || mMapView == null) {
                return;
            }
            bdlocation = location;
            navigateToLocation(location);
        }
    }
    public void navigateToLocation(BDLocation location) {
        if (isFirstLocate){
            MyLocationData.Builder locationBuilder =
                    new MyLocationData.Builder();
            locationBuilder.latitude(location.getLatitude());
            locationBuilder.longitude(location.getLongitude());
            MyLocationData locationData = locationBuilder.build();
            mBaiduMap.setMyLocationData(locationData);
            //初次进入界面定位本地
            navigateTo(location, 19f);
        }
    }
    /**
     * 移动到指定位置
     *
     * @param location
     * @param v
     */
    public void navigateTo(BDLocation location, float v) {
        LatLng ll = new LatLng(location.getLatitude(), location.getLongitude());
        MapStatusUpdate update = MapStatusUpdateFactory.newLatLng(ll);
        mBaiduMap.animateMapStatus(update);
        update = MapStatusUpdateFactory.zoomTo(v);//设置比例
        mBaiduMap.animateMapStatus(update);
        /*判断baiduMap是已经移动到指定位置*/
        if (mBaiduMap.getLocationData() != null)
            if (mBaiduMap.getLocationData().latitude == location.getLatitude()
                    && mBaiduMap.getLocationData().longitude == location.getLongitude()) {
                isFirstLocate = false;
            }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mMapView.onDestroy();
    }
}
